package com.zx;

import com.github.rholder.retry.*;
import com.google.common.base.Predicates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@RestController
public class GuavaController {

    //定义重试机制
    Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
            .retryIfException()    //设置异常重试
            .retryIfResult(Predicates.equalTo(true))    //call方法返回true重试
            .withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS))   //设置10秒后重试
            .withStopStrategy(StopStrategies.stopAfterAttempt(3)).build();  //设置重试次数 超过将出异常

    @GetMapping("/hello2")
    public String guavaRetryTest() {
        try {
            // 类需要实现callable接口
            retryer.call(() -> {
                System.out.println("业务处理中...");
                return true;   //需要重试返回true
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (RetryException e) {
            e.printStackTrace();
        }

        return "ok";
    }
}
